
import numpy as np
import cv2
from PIL import ImageGrab
import time
import multiprocessing
from ultralytics import YOLO

model = YOLO(r"F:/死神火影外挂/新建文件夹/yolov8_temp/runs\detect/train3\weights/last.pt") #加载模型
def getblood(screen_resized,value1,value2):
    blood1p= screen_resized[40:45,95:360, :]  
    blood2p= screen_resized[40:45,440:700, :] 
    
    def calculate_green_ratio(region,value):
        # 提取绿色通道
        green_channel = region[:, :, 1]
        # 判断绿色像素 (绿色值超过阈值)
        green_mask = green_channel > 100
        # 绿色像素总数
        green_pixels = np.sum(green_mask)
        # 区域总像素数
        total_pixels = region.shape[0] * region.shape[1]
        # 计算绿色占比
        green_ratio = green_pixels / total_pixels
        green_ratio= round(green_ratio,3)
        if green_ratio<value:#血量总是下降的
            if abs(green_ratio-value)<0.05:
                return green_ratio
            else:return value
        else:
            return value
    # 计算两个血条的绿色占比
    global gblood1, gblood2  # 全局变量声明
    # 计算两个血条的绿色占比，并直接更新全局变量
    gblood1 = calculate_green_ratio(blood1p,gblood1)
    gblood2 = calculate_green_ratio(blood2p,gblood1)

    return gblood1, gblood2
    
def getpower():

    return a
     

gblood1=0.97
gblood2=0.97
while(True):
    previous_time = time.time()  # 记录第一帧时间

    screen = np.array(ImageGrab.grab(bbox=(182, 73, 1100, 765)))
    screen_resized = cv2.resize(screen, (800, 600)) 
    screen_resized= cv2.cvtColor(screen_resized, cv2.COLOR_BGR2RGB)
    results = model(screen_resized, show=False, conf=0.7, save=False, verbose=False, stream=True, device='0')
    result = next(results) 
    if result.boxes is not None:
        for box in result.boxes:
            x1, y1, x2, y2 = box.xyxy[0]  # 获取检测框的四个角坐标
            class_id = int(box.cls[0])  # 类别 ID
            confidence = box.conf[0]  # 置信度

        
            cv2.rectangle(screen_resized, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
        
        # 在框内写上类别名和置信度
            label = f"Class {class_id} ({confidence:.2f})"
            cv2.putText(screen_resized, label, (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)


    gblood1,gblood2=getblood(screen_resized,gblood1,gblood2)
    cv2.imshow('window', screen_resized)  # 修正颜色转换的错误
    current_time = time.time()
    frame_interval = current_time - previous_time
    previous_time = current_time
    print(f"帧间隔: {frame_interval:.4f}秒")
    print('玩家血量',gblood1)  # 修正格式化语法

    if cv2.waitKey(25) & 0xFF == ord('q'):  # 修正 waitKey 的拼写错误
        cv2.destroyAllWindows()
        break


